/**
 * Copyright 2018 asiainfo Inc.
 **/
package com.myz.rabbitmqspring.spring.event.service.impl;


import com.myz.rabbitmqspring.spring.event.dto.EventMessage;
import com.myz.rabbitmqspring.spring.event.service.CodecFactory;
import com.myz.rabbitmqspring.spring.event.service.EventTemplate;
import com.myz.rabbitmqspring.spring.event.service.SendRefuseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 *
 * @author maoyz on 2018/8/28
 * @version: v1.0
 */
@Slf4j
public class DefaultEventTemplate implements EventTemplate {

    private AmqpTemplate eventAmqpTemplate;

    private CodecFactory defaultCodecFactory;

    public DefaultEventTemplate(AmqpTemplate eopAmqpTemplate, CodecFactory defaultCodecFactory) {
        this.eventAmqpTemplate = eopAmqpTemplate;
        this.defaultCodecFactory = defaultCodecFactory;
    }

    @Override
    public void send(String queueName, String exchangeName, Object eventContent) throws SendRefuseException {
        this.send(queueName, exchangeName, eventContent, defaultCodecFactory);
    }

    @Override
    public void send(String queueName, String exchangeName, Object eventContent, CodecFactory codecFactory) throws SendRefuseException {
        if (StringUtils.isEmpty(queueName) || StringUtils.isEmpty(exchangeName)) {
            throw new SendRefuseException("queueName exchangeName can not be empty.");
        }


        byte[] eventContentBytes = null;
        if (codecFactory == null) {
            if (eventContent == null) {
                log.warn("Find eventContent is null,are you sure...");
            } else {
                throw new SendRefuseException("codecFactory must not be null ,unless eventContent is null");
            }
        } else {
            try {
                eventContentBytes = codecFactory.serialize(eventContent);
            } catch (IOException e) {
                throw new SendRefuseException(e);
            }
        }

        // 构造成Message
        EventMessage msg = new EventMessage(queueName, exchangeName, eventContentBytes);
        try {
            eventAmqpTemplate.convertAndSend(exchangeName, queueName, msg);
        } catch (AmqpException e) {
            log.error("send event fail. Event Message : [" + eventContent + "]", e);
            throw new SendRefuseException("send event fail", e);
        }
    }
}
